package com.zmkj.cn.comm.util;


import com.zmkj.cn.comm.exception.BaseException;
import com.zmkj.cn.sys.dto.SysManagerDto;

import java.util.HashMap;
import java.util.Map;

public class ThreadLocalUtil {


    public static final String SYS_MANAGER = "sys_manager";


    public static final ThreadLocal<Map<String, Object>> THREADMAP = new ThreadLocal<Map<String, Object>>() {
        /**
         * ThreadLocal没有被当前线程赋值时或当前线程刚调用remove方法后调用get方法，返回此方法值
         */
        @Override
        protected Map<String, Object> initialValue() {

            return null;
        }
    };


    /**
     * 设置当前线程中的当前登录用户
     *
     * @param sysManager
     */
    public static void setCurrentUser(SysManagerDto sysManager) {
        ThreadLocalUtil.put(SYS_MANAGER, sysManager);

    }

    /**
     * 删除当前线程中的用户
     */
    public static void removeCurrentUser() {
        ThreadLocalUtil.remove(SYS_MANAGER);
    }


    /**
     * 获取当前线程中的当前登录用户
     */
    public static SysManagerDto getCurrentManager() {
        SysManagerDto sysManager = (SysManagerDto) ThreadLocalUtil.get(SYS_MANAGER);
        if (sysManager == null) {
            throw new BaseException("当前登录用户不存在", "当前登录用户不存在", -1);
        }
        return sysManager;
    }


    public static SysManagerDto getCurrentManagerWithNoCheck() {
        return (SysManagerDto) ThreadLocalUtil.get(SYS_MANAGER);
    }


    /**
     * 获取当前线程中的当前登录用户Id
     */
    public static String getCurrentManagerId() {
        SysManagerDto sysManager = getCurrentManager();
        return sysManager.getId() + "";
    }


    public static void init() {
        if (ThreadLocalUtil.THREADMAP.get() == null) {
            ThreadLocalUtil.THREADMAP.set(new HashMap<String, Object>());
        }
    }

    public static void destroy() {
        ThreadLocalUtil.THREADMAP.remove();
    }

    public static Object get(String key) {
        init();
        return ThreadLocalUtil.THREADMAP.get().get(key);
    }

    public static void put(String key, Object value) {
        init();
        ThreadLocalUtil.THREADMAP.get().put(key, value);
    }

    public static void remove(String key) {
        init();
        ThreadLocalUtil.THREADMAP.get().remove(key);
    }


}
